package com.blog.controller;

import com.blog.pojo.AuthorityResult;
import com.blog.pojo.User;
import com.blog.service.UserService;

import com.blog.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    public AuthorityResult login(@RequestBody Map<String,String> map){
        User user = userService.login(map);
        if (user==null){
            return new AuthorityResult(false, null, null);
        }
        String token = JwtUtil.encode(user.getUsername());
        redisTemplate.boundValueOps(user.getUsername()).set(token);

        return new AuthorityResult(true,token,user);
    }
    @GetMapping("/logout")
    public void logout(HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JwtUtil.decode(token);
        String username = claims.getSubject();
        redisTemplate.delete(username);
    }
}
